package com.ktjiaoyu.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ktjiaoyu.server.config.security.JwtTokenUtil;
import com.ktjiaoyu.server.mapper.AdminMapper;
import com.ktjiaoyu.server.mapper.RoleMapper;
import com.ktjiaoyu.server.pojo.Admin;
import com.ktjiaoyu.server.pojo.RespBean;
import com.ktjiaoyu.server.pojo.Role;
import com.ktjiaoyu.server.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author jieGe
 * @since 2022-02-12
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Autowired
    private UserDetailsService userDetailsService;

    @Resource // 注入加密工具类的bean实例对象
    private PasswordEncoder passwordEncoder;

    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.tokenHead}")
    private String tokenHead; // application.yml中配置的JWT负载中拿到开头


    @Resource
    private AdminMapper adminMapper;

    @Override
    public Admin getAdminByUserName(String username) {
        // 按用户名查询，并且enabled为true，表示当前用户是启用状态
        return adminMapper.selectOne(new QueryWrapper<Admin>().eq("username", username).eq("state", true)); // 需要注意的是t_admin表的enabled列名修改为state了
    }

    // 分页显示管理员列表, 并按用户名或手机号模糊查询
    @Override
    public IPage<Admin> selectByPage(Page<Admin> page, String query, String sort) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<Admin>();
        queryWrapper.like("name", query).or().like("phone", query);
        // 按id字段进行升序或降序排(取决限前端点击id所在列头)
        if (sort.equals("+id")) {
            queryWrapper.orderByAsc("id");
        } else {
            queryWrapper.orderByDesc("id");
        }
        Page<Admin> iPage = adminMapper.selectPage(page, queryWrapper);
// 遍历所有的操作员对象，为每个操作员对象查询出其角色列表以及每个角色所拥有的权限列表信息出来
        iPage.getRecords().stream().map((admin) -> {
            admin.setRoles(findRolesAndMenusByAdminId(admin.getId()));
            return admin;
        }).collect(Collectors.toList());
        return iPage;
    }

    @Override
    public int updateAdmin(Admin admin) {
        return adminMapper.updateById(admin);
    }

    @Override
    public boolean saveAdmin(Admin admin) {
        if (adminMapper.insert(admin) > 0) {
            return true;
        }
        return false;
    }


    @Override
    public RespBean login(String username, String password, String code, HttpServletRequest requet) {
        Admin admin = null;
        try {
            admin = (Admin) userDetailsService.loadUserByUsername(username);
        } catch (UsernameNotFoundException e) {
            return RespBean.error(e.getMessage());
        }
// 使用PasswordEncoder加密工具类中的matches对从页面上传递过来的密码password与数据库中查询出来的密码进行匹配
        if (admin == null || !passwordEncoder.matches(password, admin.getPassword())) {
            // 如果admin是空的，或者密码匹配失败就表示用户名或密码错误
            return RespBean.error("用户名或密码错误");
        }

        // 从session中取出之前在CaptchaController里生成验证并保存到了session中
        String captcha = (String) requet.getSession().getAttribute("captcha");
        if (StringUtils.isEmpty(code) || !captcha.equalsIgnoreCase(code)) {
            // 如果验证是空的，或者验证校验不通过
            return RespBean.error("验证码输入错误，请重新输入！");
        }
//判断当前用户是否禁用
        if (!admin.isEnabled()) {
            return RespBean.error("账号被禁用，请联系管理员!");
        }


        // 没有进入上面两个if判断，就说明本次登录是成功的，
        //登录成功后需要把登录的对象放到Spring Security的全文中，我们在Spring Security中获取全文时
        // 得到的将当前登录的用户对象, 其实类似于Shiro中的UsernamepasswordToken
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(admin, null, admin.getAuthorities());
        // 参数一为UserDetails对象，参数二为登录用户的密码(这里为了保密不提供)，参数三为权限列表
        //使用下面代码将authenticationToken设置到Spring Security全文中。
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        // 登录成功后就使用Jwt生成Jwt令牌。
        String token = jwtTokenUtil.genegrateToken(admin);
        Map<String, String> tokenMap = new HashMap<String, String>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead); //这个toHead的是给前端放置到请求头中的。
        tokenMap.put("avatar", admin.getUserFace()); // 头像
        return RespBean.success("登录成功!", tokenMap);

    }

    // 通过操作员用户ID查询其拥有的角色列表
    @Override
    public List<Role> findRolesByAdminId(Integer adminId) {
        return adminMapper.findRolesByAdminId(adminId);
    }

    @Resource
    private RoleMapper roleMapper;

    //通过用户ID查询用户所拥有的角色列表，以及每个角色所拥有的权限列表
    @Override
    public List<Role> findRolesAndMenusByAdminId(Integer adminId) {
        List<Role> roles = adminMapper.findRolesByAdminId(adminId).stream().map((role) -> {
            //将角色下的权限查询出来
            role.setChildren(roleMapper.findMenuByRole(role.getId()));
            return role;
        }).collect(Collectors.toList());
        return roles;
    }

    @Override
    public List<String> findMenuUrIByAdminId(Integer adminId) {
        return adminMapper.findMenuUrlByAdminId(adminId);
    }


}
